#ifdef USE_DEVIL
#include "stdafx.h"
#include "Math3D.h"
#include "DevILLoader.h"

// Hack: there's a clash with wxWidgets unicode
#undef _UNICODE
#include <IL/il.h>
#include <IL/ilu.h>

bool DevILLoader::ilInitialized = false;
DevILLoader::DevILLoader()
{
	if(!ilInitialized)
	{
		ilInit();
		iluInit();
		ilInitialized = true;
	}
}

DevILLoader::~DevILLoader()
{
}

bool DevILLoader::CanLoadTexture(const wxString &filename) const
{
	return false;
}

bool DevILLoader::LoadTexture(Texture *texture, const wxString &filename, int offset) const
{
	ILuint image;

	if(filename.empty())
		return false;

	// Create the image.
	ilGenImages(1, &image);
	ilBindImage(image);
	ilActiveMipmap(0);

	// Load the image.
	if(ilLoadImage(filename.utf8_str()) == IL_FALSE)
	{
		LWarning(_("Failed to load texture '%s': %s\n"), filename.c_str(), iluErrorString(ilGetError()));
		return false;
	}

	// Get image data.
	int width = ilGetInteger(IL_IMAGE_WIDTH);
	int height = ilGetInteger(IL_IMAGE_HEIGHT);
	int bpp = ilGetInteger(IL_IMAGE_BITS_PER_PIXEL);
	int mips = Min(ilGetInteger(IL_NUM_MIPMAPS)+1, 4);

	// Store some texture data.
	texture->bits = bpp;
	texture->mips = mips;
	texture->realWidth = width;
	texture->realHeight = height;

	ILenum format = ilGetInteger(IL_IMAGE_FORMAT);
	ILenum type = ilGetInteger(IL_IMAGE_TYPE);

	size_t size = width*height*(bpp/8);
	for(int i = 0; i < mips; i++)
	{
		texture->mip[i] = new char[size >> i*2];
		ilActiveMipmap(i);
		ilCopyPixels(0, 0, 0, width, height, 1, format, type, texture->mip[i]);

		width /= 2;
		height /= 2;
	}
	texture->surface = texture->mip[0];

	// Delete the image
	ilDeleteImages(1, &image);
	return true;
}

#endif //USE_DEVIL
